package org.codeart.map.remote;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.codeart.common.response.TraceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class TraceClient {

    @Value("${system.map.key}")
    private String key;

    @Value("${system.map.sid}")
    private Integer sid;

    @Value("${system.map.trace-service-add-api}")
    private String traceApi;

    @Autowired
    private RestTemplate restTemplate;

    public TraceResponse add(Integer tid) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>() {{
            add("key", key);
            add("sid", sid);
            add("tid", tid);
        }};
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        String json = restTemplate.postForObject(traceApi, request, String.class);
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONObject data = jsonObject.getJSONObject("data");
        // 轨迹id和轨迹名称
        Integer trid = data.getInteger("trid");
        String trname = StrUtil.isEmpty(data.getString("trname")) ? "" : data.getString("trname");

        TraceResponse traceResponse = new TraceResponse();
        traceResponse.setTrid(trid).setTrname(trname);
        return traceResponse;
    }

}
